package com.limespot.api.misc;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

public final class SetUtils<T> {

	public Set<T> union(Set<T> s1, Set<T> s2) {
		if (s1 == null) return new HashSet<T>(s2);
		if (s2 == null) return new HashSet<T>(s1);
		Set<T> res = new HashSet<T>();
		for (T t : s1) res.add(t);
		for (T t : s2) res.add(t);
		return res;
	}
	
	public Set<T> intersection(Set<T> s1, Set<T> s2) {
		if (s1 == null) return Collections.emptySet();
		if (s2 == null) return Collections.emptySet();
		Set<T> res = new HashSet<T>();
		if (s1.size() < s2.size()) {
			intersection(s1,s2,res);
		} else {
			intersection(s2,s1,res);
		}
		return res;
	}
	
	private void intersection(Set<T> s1, Set<T> s2, Set<T> res) {
		for (T t : s1) {
			if (s2.contains(t)) res.add(t);
		}		
	}
}
